package cn.jtcoding.common.framework.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author jason.tang
 * @Date 2020/11/12 16:38
 * @Desc 分批处理数据
 */

@Slf4j
public final class BatchUtils<T> {

    /**
     * 分批处理数据
     * @param <T>
     * @param list 数据源
     * @param batchCount 每次处理的数量
     * @param callback 每次处理的结果
     */
    public static <T> void batchHandler(List<T> list, int batchCount, BatchCallback<T> callback) {
        int size = list.size();
        int time = size % batchCount == 0 ? size / batchCount : size / batchCount + 1;
        log.info("size: {}, time: {}, batch count: {}", size, time, batchCount);
        for (int i = 0; i < time; i++) {
            List<T> portionList = list.subList(i * batchCount, Math.min((i + 1) * batchCount, size));
            callback.handler(portionList);
        }
    }

    public interface BatchCallback<T> {
        void handler(List<T> data);
    }
}
